<%--
  Created by IntelliJ IDEA.
  User: leixiaolong
  Date: 2018/9/20
  Time: 下午5:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/include.jsp" %>

<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="/static/css/rpt-condition.css" media="all" type="text/css">

    <style>
        .layui-form-label {
            width: 160px !important;
        }
    </style>

    <style>
        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
        .layui-table-cell {
            overflow: visible !important;
        }

        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select {
            /*margin-top: -10px;*/
            /*margin-left: -15px;*/
            /*margin-right: -15px;*/
            /*solid: #d2d2d2;*/
            /*border: 1px;*/
        }

        /* 设置下拉框的高度与表格单元相同 */
        .layui-input, .layui-select, .layui-textarea {
            height: 30px !important;
        }

    </style>

    <style>
        .col-select-lg {
            margin-top: 10px;
            height: 30px;
            width: 300px;
            min-width: 200px;
            max-width: 600px;
        }

        .layui-input-inline {
            min-width: 300px;
            max-width: 600px;
        }
    </style>
</head>
<body class="layui-bg-gray">
<div class="layui-row layui-col-space10" style="margin: 10px; background-color: white">
    <div class="layui-container">
        <div class="layui-row layui-form">
            <div class="layui-col-md6 layui-hide">
                <div class="layui-form-item">
                    <label class="layui-form-label ">销售退货单id：</label>
                    <input type="text" id="key_id" class="layui-input-inline dom-add-input">
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">销售客户：</label>
                    <div class="layui-input-inline">
                        <select class="layui-form-select" id="cust_code" lay-filter="cust_code">
                            <option value="" selected>全部</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">销售退货类型：</label>
                    <div class="layui-input-inline">
                        <select class="layui-form-select" id="back_type" lay-filter="back_type">
                            <option value="" selected>全部</option>
                        </select>
                    </div>
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
                <%--<div class="layui-form-item">--%>
                    <%--<label class="layui-form-label">源订单类型：</label>--%>
                    <%--<div class="layui-input-inline">--%>
                        <%--<select class="layui-form-select" id="sour_sale_type" lay-filter="sour_sale_type">--%>
                            <%--<option value="" selected>全部</option>--%>
                        <%--</select>--%>
                    <%--</div>--%>
                <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">源销售订单id：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="sour_sale_id" class="layui-input-inline dom-add-input">
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">供应商：</label>
                    <div class="layui-input-inline">
                        <select class="layui-form-select" id="cont_code" lay-filter="cont_code">
                            <option value="" selected>全部</option>
                        </select>
                    </div>
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
            <%--<div class="layui-form-item">--%>
            <%--<label class="layui-form-label">供货商编码：</label>--%>
            <%--<div class="layui-input-inline">--%>
            <%--<input type="text" id="cont_code" class="layui-input-inline dom-add-input">--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<div class="layui-col-md6">--%>
            <%--<div class="layui-form-item">--%>
            <%--<label class="layui-form-label">供货商联系人名称：</label>--%>
            <%--<div class="layui-input-inline">--%>
            <%--<input type="text" id="cont_name" class="layui-input-inline dom-add-input">--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<div class="layui-col-md6">--%>
            <%--<div class="layui-form-item">--%>
            <%--<label class="layui-form-label">供货商联系人电话：</label>--%>
            <%--<div class="layui-input-inline">--%>
            <%--<input type="text" id="cont_phone" class="layui-input-inline dom-add-input">--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">退货日期：</label>
                    <input id="back_date" type="text" class="dom-add-input" style="text-align: center"
                           placeholder="yyyy-MM-dd">
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
            <%--<div class="layui-form-item">--%>
            <%--<label class="layui-form-label">退货仓库：</label>--%>
            <%--<div class="layui-input-inline">--%>
            <%--<input type="text" id="stor_code" class="layui-input-inline dom-add-input">--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">退货仓库：</label>
                    <div class="layui-input-inline">
                        <select class="layui-form-select" id="stor_code" lay-filter="stor_code">
                            <option value="" selected>全部</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">退货地址：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="address" class="layui-input-inline dom-add-input">
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">摘要：</label>
                    <input type="text" id="abstract" class="layui-input-inline dom-add-input">
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
                <%--<div class="layui-form-item">--%>
                    <%--<label class="layui-form-label">源采购订单类型：</label>--%>
                    <%--<div class="layui-input-inline">--%>
                        <%--<select class="layui-form-select" id="sour_purc_type" lay-filter="sour_purc_type">--%>
                            <%--<option value="" selected>全部</option>--%>
                        <%--</select>--%>
                    <%--</div>--%>
                <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">源采购订单id：</label>
                    <input type="text" id="sour_purc_id" class="layui-input-inline dom-add-input">
                </div>
            </div>
        </div>
    </div>
</div>
<div style="margin: 10px; background-color: white;">
    <table class="layui-hide" id="tab_back_update" lay-filter="back-add-filter"></table>
</div>

<div class="layui-btn-container" style="float: right; margin-right: 10%">
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="confirm">提交</button>
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="cancel">取消</button>
</div>
</body>

<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/table-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/tax-math.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-math.js"></script>

<script type="text/html" id="toolbarAdd">
    <div class="layui-btn-group" style="float: right; margin-right: 10px;">
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="add">新增</button>
    </div>
</script>

<script type="text/html" id="templateSelect">
    <select id='select_{{d.id}}' layui-filter="selectfish">
        <option value="" selected>请选择</option>
    </select>
</script>

<script type="text/html" id="backOrderDetailDel">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
    </div>
</script>

<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-date.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/moment.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/comm-data.js"></script>
<script>
    var recordNum = 0;
    // var taxRate = 0;
    var gooddata = [];

    layui.use(["element", "form", "layer", "table", "jquery", "laydate"], function () {
        var element = layui.element, layer = layui.layer, table = layui.table, $ = layui.jquery;
        var form = layui.form, laydate = layui.laydate;
        var params = {
            sysCode : '12'
        }
        // var params1 = {
        //     sysCode : '13'
        // }
        // var params2 = {
        //     sysCode : '13'
        // }
        initCodeTableSelect("back_type","/base/getSysCodeList",params);
        // initCodeTableSelect("sour_sale_type","/base/getSysCodeList",params1);
        // initCodeTableSelect("sour_purc_type","/base/getSysCodeList",params1);
        getGoodsInfo(gooddata);
        initSuppInfoSelect("cont_code");
        initStorSelect("stor_code");
        initCustInfoSelect("cust_code");
        table.set({
            limit: 50
        });
        var tableIns = table.render({
            id: 'tab_back_update',
            elem: '#tab_back_update',
            toolbar: '#toolbarAdd',
            defaultToolbar: [],
            cellMinWidth: 90,
            data: [],
            // even: true, //隔行背景
            height: 'full-350',
            cols: [[
                {field: 'id', title: '序号', align: 'center'},
                {field: 'keyId', title: '销售订单流水id', align: 'center', hide: true},
                {field: 'goodCode', title: '商品编码', align: 'center', hide: true},
                {field: 'goodName', title: '商品名称', align: 'center', hide: true},
                {
                    field: 'goodName', title: '商品名称', minWidth: 140, templet: function (d) {
                        return loadGoodSelect(d.id, gooddata, d.goodCode);
                        // d.goodName;
                    }, align: 'center'
                },
                {field: 'varietyCode', title: '品种编码', align: 'center', hide: true},
                {field: 'varietyName', title: '品种名称', align: 'center', hide: true},
                {field: 'standardName', title: '商品规格', align: 'center'},
                {field: 'unit', title: '商品单位', align: 'center'},
                // {field: 'source', title: '商品来源', edit: true, align: 'center'},
                {
                    field: 'outTaxRate', title: '商品销项税率', align: 'center', templet: function (d) {
                        return getFloat(d.outTaxRate);
                    }
                },
                {
                    field: 'price', title: '税后价格', edit: true, align: 'center', templet: function (d) {
                        return getFloat(d.price);
                    }
                },
                {
                    field: 'noTaxPrice', title: '商品价格', align: 'center', templet: function (d) {
                        return computeNoTaxPrice(d.price, d.outTaxRate);
                    }
                },
                {
                    field: 'amount', title: '商品数量', edit: true, align: 'center', templet: function (d) {
                        return getFloat(d.amount);
                    }
                },
                {
                    field: 'bal', title: '税后金额', align: 'center', templet: function (d) {
                        if (typeof(d.price) == 'undefined' || typeof(d.amount) == 'undefined') {
                            return 0;
                        }
                        return getFloat(d.price * d.amount);
                    }
                },
                {
                    field: 'noTaxBal', title: '商品金额', align: 'center', templet: function (d) {
                        if (d.amount == null || d.amount.length === 0) {
                            return 0;
                        }

                        return round((computeNoTaxPrice(d.price, d.outTaxRate)) * d.amount, 2);
                    }
                },
                {
                    field: 'estOutTax', title: '预估销项税', align: 'center', templet: function (d) {
                        if (d.amount == null || d.amount.length === 0) {
                            return 0;
                        }
                        return round((getFloat(d.price) - computeNoTaxPrice(d.price, d.outTaxRate)) * d.amount, 2);
                    }
                },
                {field: 'billAbstract', title: '摘要', align: 'center', edit: true},
                {field: 'operator', title: '操作', fixed: 'right', templet: '#backOrderDetailDel'}]],
            done: function () {
                console.log("渲染表格 over");
                form.render();
            },
            page: false
        });

        form.render('select');

        table.on('toolbar(back-add-filter)', function (obj) {
            switch (obj.event) {
                case 'add':
                    debugger
                    layer.msg('添加');
                    var newdata = table.cache["tab_back_update"];
                    var newline = {
                        'id': ++recordNum
                    };

                    if(recordNum > 50){
                        layer.msg("销售订单不能超过50条！");
                        break;
                    }
                    newdata.push(newline);
                    table.reload('tab_back_update', {
                        data: newdata
                    });

                    loadGoodSelect(recordNum, gooddata);
                    form.render('select');
                    break;
                case 'del':
                    layer.msg('删除');
                    break;
                case 'update':
                    layer.msg('编辑');
                    break;
            }
            ;
        });


        table.on('tool(back-add-filter)', function (obj) {
            switch (obj.event) {
                case 'delete':
                    layer.confirm("是否删除本条记录", {icon: 3}, function (index) {
                        obj.del();
                        layer.close(index);
                    });
                    break;
            }
        });

        active = {
            confirm: function confirm() {
                var data = table.cache.tab_back_update;

                var newdata = trimAllArray(data);

                request = {
                    "id": $('#key_id').val(),
                    "custCode": $('#cust_code').find('option:selected').val(),
                    "custName": $('#cust_code').find('option:selected').text(),
                    "sourSaleId": $('#sour_sale_id').val(),
                    "backType": $('#back_type').find('option:selected').val(),
                    // "sourSaleType": $('#sour_sale_type').find('option:selected').val(),
                    "suppCode": $('#cont_code').find('option:selected').val(),
                    "suppLinkName": $('#cont_code').find('option:selected').text(),
                    "backDate": $('#back_date').val(),
                    // "suppLinkTel": $('#cont_phone').val(),
                    "storCode": $('#stor_code').val(),
                    // "sourPurcType": $('#sour_purc_type').find('option:selected').val(),
                    "sourPurcId": $('#sour_purc_id').val(),
                    "address": $('#address').val(),
                    "billAbstract": $('#abstract').val(),
                    "backDetailData": newdata
                };
                var reqBody = (JSON.stringify(request));

                $.ajax({
                    type: "POST",
                    url: "/sale/marketBackModify",
                    contentType: 'application/json',
                    dataType: 'json',//服务端返回数据类型
                    data: reqBody,
                    async: false,
                    success: function (data) {
                        if (data.rspCode == 'RSP000000') {
                            layer.msg("修改销售订单成功,订单编号:" + data.data);
                        } else {
                            layer.msg("修改销售订单失败:" + data.rspMsg);
                            return;
                        }
                    },
                    error: function (data) {
                        console.log("系统异常:" + data);
                        layer.msg("系统异常,请联系管理员");
                    }
                });

                if (true) {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);

                    parent.layui.table.reload("tab_back_apply", {});
                }
            },
            cancel: function cancel() {
                layer.msg("关闭弹出订单录入");
                var parent_layer = parent.layer;
                var index = parent.layer.getFrameIndex(window.name); //获取当前窗体索引

                parent.layer.close(index);
                parent.layui.table.reload("tab_back_apply", {});
            }
        };
        function updateRowItemBySaleRow(tableId, rowdata) {
            layui.use("table", function () {
                var table = layui.table;
                var data = table.cache[tableId];
                var newdata = [];
                data.forEach(function (value, index, array) {
                    if (parseInt(value.id) === parseInt(rowdata.id)) {
                        //更新新的信息
                        value.goodCode = rowdata.goodCode;
                        value.goodName = (typeof(rowdata.goodName) == 'undefined' ? '' : rowdata.goodName);
                        value.varietyCode = (typeof(rowdata.varietyCode) == 'undefined' ? '' : rowdata.varietyCode);
                        value.varietyName = (typeof(rowdata.varietyName) === 'undefined' ? '' : rowdata.varietyName);
                        value.standardName = (typeof(rowdata.standardName) === 'undefined' ? '' : rowdata.standardName);
                        value.unit = (typeof(rowdata.unit) === 'undefined' ? '' : rowdata.unit);
                        value.outTaxRate = (typeof(rowdata.outTaxRate) === 'undefined' ? "0" : rowdata.outTaxRate);
                        // value.price = (typeof(rowdata.price) === 'undefined' ? "0" : rowdata.price);
                        value.noTaxPrice = (typeof(rowdata.noTaxPrice) === 'undefined' ? "0" : rowdata.noTaxPrice);
                        // value.amount = (typeof(rowdata.amount) === 'undefined' ? "0" : rowdata.amount);
                        value.bal = (typeof(rowdata.bal) === 'undefined' ? "0" : rowdata.bal);
                        value.noTaxBal = (typeof(rowdata.noTaxBal) === 'undefined' ? "0" : rowdata.noTaxBal);
                        value.estOutTax = (typeof(rowdata.estOutTax) === 'undefined' ? "0" : rowdata.estOutTax);
                        value.digest = (typeof(rowdata.digest) === 'undefined' ? "" : rowdata.digest);
                        newdata.push(value);
                    } else {
                        newdata.push(value);
                    }
                });

                table.reload(tableId, {
                    data: newdata
                });
            });
        }

        function updateRowSaleItem(tableId, rowdata, isClear){
            if(!isClear){
                return updateRowItemBySaleRow(tableId, rowdata);
            }

            layui.use("table", function () {
                var table = layui.table;
                var data = table.cache[tableId];
                var newdata = [];
                data.forEach(function (value, index, array) {
                    if (parseInt(value.id) === parseInt(rowdata.id)) {
                        //更新新的信息
                        value = {};
                        value.id = rowdata.id;
                        newdata.push(value);
                    } else {
                        newdata.push(value);
                    }
                });

                table.reload(tableId, {
                    data: newdata
                });
            });
        }
        form.on('submit', function (data) {
            var elem = data.elem;
            active[$(this).data("type")].call(this, elem);
        });
        /**
         * 监听select下拉框事件
         */
        form.on('select', function (data) {
            //监听数据处理
            var goodCode = data.value;
            if(data.elem.id == "sale_type"
                || data.elem.id == "sour_sale_type"
                || data.elem.id == "cust_code"
                || data.elem.id == "back_type"
                || data.elem.id == "cont_code"
                || data.elem.id == "sour_purc_type"
                || data.elem.id == "stor_code"){
                return ;
            }

            //获取当前行记录
            var rowdata = getRowItemById("tab_back_update", data.elem.id.substring(data.elem.id.indexOf("_") + 1, data.elem.id.length));

            //获取商品信息
            var goodinfo = getGoodInfoById(goodCode);

            //获取税率
            // if (taxRate == null || taxRate <= 0) {
            //     taxRate = getTaxRate();
            // }
            //get商品信息 goodInfo
            var gooddata = {
                "id": rowdata.id,
                "goodCode": data.value,
                'goodName': goodinfo.goodName,
                "varietyCode": goodinfo.varietyCode,
                "outTaxRate": goodinfo.taxRate,
                "varietyName": goodinfo.varietyName,
                "standardName": goodinfo.standardName,
                "unit": goodinfo.unit
            };

            var isClear = false;
            if (data.value == null || data.value.trim().length === 0) {
                var rowid = gooddata.id;
                gooddata = {};
                gooddata.id = rowid;
                isClear = true;
            }

            //对商品信息更新赋值
            updateRowSaleItem("tab_back_update", gooddata, isClear);
        });
        /**
         * 监听编辑单元格事件
         */
        table.on('edit(back-add-filter)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data;
            obj.update(data);
            form.render('select');
        });
    });

    function init(paramData) {
        var params = {id: paramData.id};
        debugger;
        layui.use(["form", "jquery","table", "laydate"], function () {
            var form = layui.form, $ = layui.jquery, table = layui.table, laydate = layui.laydate;
            $.ajax({
                url: "/sale/toUpdateMarketBackPage",
                type: 'POST',
                sync: false,
                data: params,
                success: function (data) {
                    $('#key_id').val(data.data.id);
                    $('#cust_code').val(data.data.custCode);
                    $('#cust_name').val(data.data.custName);
                    $('#back_type').val(data.data.backType);
                    // $('#sour_sale_type').val(data.data.sourSaleType);
                    $('#sour_sale_id').val(data.data.sourSaleId);
                    $('#cont_code').val(data.data.suppCode);
                    $('#cont_name').val(data.data.suppLinkName);
                    renderDate('back_date',data.data.backDate);
                    // $('#cont_phone').val(data.data.suppLinkTel);
                    $('#stor_code').val(data.data.storCode);
                    $('#address').val(data.data.address);
                    $('#abstract').val(data.data.billAbstract);
                    // $('#sour_purc_type').val(data.data.sourPurcType);
                    $('#sour_purc_id').val(data.data.sourPurcId);
                    form.render('select');
                    var list = data.data.saleBackDetailData;
                    var newdata = table.cache["tab_back_update"];
                    $.each(list, function (i, n) {  //回显到表格
                        var newline = {
                            'id': i,
                            'keyId': list[i].keyId,
                            'goodCode': list[i].goodCode,
                            'varietyCode': list[i].varietyCode,
                            'varietyName': list[i].varietyName,
                            'standardName': list[i].standardName,
                            'unit': list[i].unit,
                            'source': list[i].source,
                            'outTaxRate': list[i].outTaxRate,
                            'bal': list[i].bal,
                            'price': list[i].price,
                            'noTaxPrice': list[i].noTaxPrice,
                            'amount': list[i].amount,
                            'noTaxBal': list[i].noTaxBal,
                            'estOutTax': list[i].estOutTax,
                            'billAbstract': list[i].billAbstract
                        };
                        newdata.push(newline);//右侧加入
                    });
                    table.reload("tab_back_update", {
                        data: newdata
                    });
                    layer.msg("交易成功,页面渲染完成！");
                },
                fail: function (data) {
                    layer.msg("交易失败, message:" + data.rspMsg)
                }
            });
        });
    }
</script>
</html>
